package cn.lzd.mr.mroverride.combine;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.CombineTextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Created by lzd on 2018/6/28.
 */
public class CombineDemo {

    public static class Mymapper extends Mapper<Object, Text, IntWritable, Text> {

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String str = value.toString();
            context.write(new IntWritable(str.hashCode()), new Text(str));
        }

    }

    public static class Myreducer extends Reducer<IntWritable, Text, NullWritable, Text> {

        @Override
        protected void reduce(IntWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            super.reduce(key, values, context);
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration configuration = new Configuration();

        Job job = Job.getInstance(configuration);
        job.setJarByClass(CombineDemo.class);
        job.setMapOutputKeyClass(IntWritable.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(Text.class);

        job.setMapperClass(CombineDemo.Mymapper.class);
        job.setReducerClass(CombineDemo.Myreducer.class);

        /**
         * 小文件合并,够64M合并，最大不超过128M
         */
        job.setInputFormatClass(CombineTextInputFormat.class);
        CombineTextInputFormat.setMinInputSplitSize(job,65536);//64M
        CombineTextInputFormat.setMaxInputSplitSize(job,131072);//128M

        FileInputFormat.setInputPaths(job, new Path("/G:/gaos/combine/*.txt"));
        FileOutputFormat.setOutputPath(job, new Path("/G:/gaos/combine/out/"));

        System.exit(job.waitForCompletion(true) ? 0 : 1);

    }
}
